import axios from 'axios'
import { ElMessage, ElNotification, ElMessageBox, ElLoading } from 'element-plus'
import { getToken } from './token'
import router from '@/router'

const axiosConfig = {
    baseURL: import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8000',
    timeout: import.meta.env.VITE_API_TIMEOUT || 10 * 1000
}

const instance = axios.create(axiosConfig)

// 加载中实例
let loadingInstance = null

// 请求拦截器
instance.interceptors.request.use(
    config => {
        // 显示加载中
        loadingInstance = ElLoading.service({
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
        })

        // 根据请求类型设置 Content-Type
        if (!config.headers['Content-Type'] && config.method === 'post') {
            config.headers['Content-Type'] = 'application/json'
        }

        // 设置 token
        const token = getToken()
        console.log('Get current token:', token)
        if (token) {
            config.headers['Authorization'] = token
            console.log('Request headers:', config.headers)
        }

        return config
    },
    error => {
        loadingInstance?.close()
        return Promise.reject(error)
    }
)

// 响应拦截器
instance.interceptors.response.use(
    response => {
        loadingInstance?.close()

        const { code, data, message, errors } = response.data

        // 处理成功响应
        if (code === 200) {
            if (message) {
                ElNotification({
                    type: 'success',
                    title: '成功',
                    message: message
                })
            }
            return data
        }

        // 处理错误响应
        switch (code) {
            case 400:
                if (Array.isArray(errors) && errors.length > 0) {
                    errors.forEach(err => {
                        ElMessage.error(err)
                    })
                }
                break
            case 401:
                ElMessageBox.confirm(
                    '登录状态已过期，请重新登录',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    router.push('/login')
                })
                break
            default:
                ElMessage.error(message || '发生未知错误')
        }

        return Promise.reject(response.data)
    },
    error => {
        loadingInstance?.close()

        if (!error.response) {
            ElMessage.error('网络错误，请检查网络连接')
            return Promise.reject(error)
        }

        const { code, message, errors } = error.response.data || {}

        // 处理后端返回的错误
        if (code) {
            switch (code) {
                case 400:
                    if (Array.isArray(errors) && errors.length > 0) {
                        errors.forEach(err => {
                            ElMessage.error(err)
                        })
                    }
                    break
                case 401:
                    ElMessageBox.confirm(
                        '登录状态已过期，请重新登录',
                        '提示',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(() => {
                        router.push('/login')
                    })
                    break
                default:
                    ElMessage.error(message || '发生未知错误')
            }
        } else {
            ElMessage.error(error.message || '发生未知错误')
        }

        return Promise.reject(error)
    }
)

// HTTP 方法封装
const http = {
    get(url, params, config = {}) {
        console.log('Making GET request to:', url)
        return instance.get(url, { params, ...config })
    },

    post(url, data, config = {}) {
        console.log('Making POST request to:', url)
        return instance.post(url, data, config)
    },

    put(url, data, config = {}) {
        console.log('Making PUT request to:', url)
        return instance.put(url, data, config)
    },

    delete(url, params, config = {}) {
        console.log('Making DELETE request to:', url)
        return instance.delete(url, { params, ...config })
    },

    // 带确认框的删除方法
    async confirmDelete(url, params, config = {}) {
        try {
            await ElMessageBox.confirm(
                '确定要删除这条数据吗？',
                '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            )
            return await this.delete(url, params, config)
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 上传文件
    upload(url, file, config = {}) {
        const formData = new FormData()
        formData.append('file', file)
        return instance.post(url, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            ...config
        })
    }
}

export default http


// // GET 请求
// http.get('/api/users', { page: 1 })
//     .then(data => {
//         // data 是响应中的 data 字段
//         console.log(data)
//     })
//     .catch(error => {
//         // 错误处理已在拦截器中完成
//         console.error(error)
//     })

// // POST 请求
// http.post('/api/users', {
//     name: 'test',
//     email: 'test@example.com'
// })

// // 带确认框的删除
// http.confirmDelete('/api/users/1')

// // 上传文件
// http.upload('/api/upload', fileObject)